import React, { ReactChild } from "react";
import { useState } from "react";
import ReactDOM from "react-dom";
import style from "./Modal.module.scss";

function Modal({
  children,
  closeModal,
}: {
  children: React.ReactChild;
  closeModal: () => void;
}) {
  const domEl = document.querySelector("#modal");
  if (!domEl) return null;

  return ReactDOM.createPortal(
    <>
      <div className={style.modalMask}></div>
      <div className={style.modalWrap} onClick={closeModal}>
        <div className={style.modal}>
          <div className={style.modalContent}>
            {/* 这里使用父组件的title*/}
            <div className={style.modalHeader}>
              查看
              <div className={style.modalClose} onClick={closeModal}>X</div>
            </div>
            <div className={style.modalBody}>
              {children}
            </div>
            <div className={style.modalFooter}>
              <button className="btn" onClick={closeModal}>取消</button>
              <button className="btn btn-primary ml-10" onClick={closeModal}>确认</button>
            </div>
          </div>
        </div>
      </div>
    </>,
    domEl
  );
}

export function useModal() {
  const [isVisible, setIsVisible] = useState(false);

  const show = () => setIsVisible(true);
  const hide = () => setIsVisible(false);

  const RenderModal = ({ children }: { children: ReactChild }) => {
    return <>{isVisible && <Modal closeModal={hide}>{children}</Modal>}</>;
  };

  return { show, hide, RenderModal };
}
